# -*- coding: utf-8 -*-
"""
销售控制层

负责处理销售相关的HTTP请求和响应
"""
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field
from typing import Optional, List
from app.services.sales_service import SalesService

router = APIRouter(
    prefix="/sales",
    tags=["sales"],
    responses={404: {"description": "Not found"}}
)

# 初始化服务层
sales_service = SalesService()

# Pydantic 模型
class SalesStatisticsResponse(BaseModel):
    goods_id: str = Field(..., description="商品ID")
    goods_name: str = Field(..., description="商品名称")
    spec_id: Optional[str] = Field(None, description="规格ID")
    spec_name: Optional[str] = Field(None, description="规格名称")
    total_sales_quantity: int = Field(..., description="总销售数量")
    total_sales_amount: float = Field(..., description="总销售金额")
    total_paid_amount: float = Field(..., description="总实付金额")
    order_count: int = Field(..., description="订单数量")
    avg_price: float = Field(..., description="平均单价")
    last_sale_date: Optional[str] = Field(None, description="最后销售日期")
    first_sale_date: Optional[str] = Field(None, description="首次销售日期")

class TopSellingGoodsResponse(BaseModel):
    rank: int = Field(..., description="排名")
    goods_id: str = Field(..., description="商品ID")
    goods_name: str = Field(..., description="商品名称")
    total_sales_quantity: int = Field(..., description="总销售数量")
    total_sales_amount: float = Field(..., description="总销售金额")
    order_count: int = Field(..., description="订单数量")
    avg_price: float = Field(..., description="平均单价")


@router.get("/statistics")
async def get_sales_statistics(
    goods_id: Optional[str] = Query(None, description="商品ID（可选，用于查询特定商品）"),
    page: int = Query(1, gt=0, description="页码"),
    page_size: int = Query(10, gt=0, le=100, description="每页数量"),
    start_date: Optional[str] = Query(None, description="开始日期 (YYYY-MM-DD)"),
    end_date: Optional[str] = Query(None, description="结束日期 (YYYY-MM-DD)")
):
    """获取商品销售统计"""
    try:
        result = sales_service.get_goods_sales_statistics(
            goods_id=goods_id,
            page=page,
            page_size=page_size,
            start_date=start_date,
            end_date=end_date
        )
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取销售统计失败: {str(e)}")


@router.get("/detail/{goods_id}")
async def get_goods_sales_detail(goods_id: str):
    """获取单个商品的销售详情"""
    try:
        result = sales_service.get_single_goods_sales_detail(goods_id)
        return result
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取商品销售详情失败: {str(e)}")


@router.get("/top-selling")
async def get_top_selling_goods(
    limit: int = Query(10, gt=0, le=100, description="返回数量限制"),
    start_date: Optional[str] = Query(None, description="开始日期 (YYYY-MM-DD)"),
    end_date: Optional[str] = Query(None, description="结束日期 (YYYY-MM-DD)")
):
    """获取销售量排行榜"""
    try:
        result = sales_service.get_top_selling_goods(
            limit=limit,
            start_date=start_date,
            end_date=end_date
        )
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取销售排行榜失败: {str(e)}")


@router.get("/summary")
async def get_sales_summary(
    start_date: Optional[str] = Query(None, description="开始日期 (YYYY-MM-DD)"),
    end_date: Optional[str] = Query(None, description="结束日期 (YYYY-MM-DD)")
):
    """获取销售汇总数据"""
    try:
        result = sales_service.get_sales_summary(
            start_date=start_date,
            end_date=end_date
        )
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取销售汇总失败: {str(e)}") 